﻿(function ($) {
    $.fn.extend({
        //按钮点击事件
        btnOnClick: function (func) {
            $(this).click(function () {
                eval('$.ButtonClick.' + func + '()');
            });
        },
    });

    $.gridListReload = function () {
        var $initlist = $.currentWindow().$("#initlist");
        var $btnlist = $.currentWindow().$("#btnlist");
        var $gridList = $.currentWindow().$("#gridList");

        $initlist.show(300);
        $btnlist.hide(300);
        $gridList.resetSelection();
        $gridList.trigger("reloadGrid");
    }

    $.currentWindow = function () {
        var iframeId = top.$(".Oceansoft_Iframe:visible").attr("id");
        return top.frames[iframeId];
    }

    $.reload = function () {
        location.reload();
        return false;
    }

    $.loading = function (bool, text) {
        var $loadingpage = top.$("#loadingPage");
        var $loadingtext = $loadingpage.find('.loading-content');
        if (bool) {
            $loadingpage.show();
        } else {
            if ($loadingtext.attr('istableloading') == undefined) {
                $loadingpage.hide();
            }
        }
        if (!!text) {
            $loadingtext.html(text);
        } else {
            $loadingtext.html("数据加载中，请稍后…");
        }
        $loadingtext.css("left", (top.$('body').width() - $loadingtext.width()) / 2 - 50);
        $loadingtext.css("top", (top.$('body').height() - $loadingtext.height()) / 2);
    }

    $.request = function (name) {
        var search = location.search.slice(1);
        var arr = search.split("&");
        for (var i = 0; i < arr.length; i++) {
            var ar = arr[i].split("=");
            if (ar[0] == name) {
                var s = arr[i].substr(name.length + 1, arr[i].length - name.length - 1);
                if (unescape(s) == 'undefined') {
                    return "";
                } else {
                    return unescape(s);
                }
            }
        }
        return "";
    }

    $.modalOpen = function (options) {
        var defaults = {
            id: null,
            title: '系统窗口',
            width: "100px",
            height: "100px",
            url: '',
            shade: 0.3,
            btn: ['确认', '关闭'],
            btnclass: ['btn btn-primary', 'btn btn-danger'],
            callBack: null
        };
        var options = $.extend(defaults, options);
        var _width = top.$(window).width() > parseInt(options.width.replace('px', '')) ? options.width : top.$(window).width() + 'px';
        var _height = top.$(window).height() > parseInt(options.height.replace('px', '')) ? options.height : top.$(window).height() + 'px';
        top.layer.open({
            id: options.id,
            type: 2,
            shade: options.shade,
            title: options.title,
            fix: false,
            area: [_width, _height],
            content: options.url,
            btn: options.btn,
            btnclass: options.btnclass,
            yes: function () {
                options.callBack(options.id);
            }, cancel: function () {
                return true;
            }
        });
    }

  

    $.modalConfirm = function (content, callBack) {
        top.layer.confirm(content, {
            icon: "fa fa-question-circle",
            title: "系统提示",
            btn: ['确认', '取消'],
            btnclass: ['btn btn-primary', 'btn btn-danger']
        }, function () {
            callBack(true);
        }, function () {
            callBack(false)
        });
    }
    $.modalAlert = function (content, type) {
        var icon = "";
        var title = "";
        if (type == 'success') {
            icon = "fa fa-check-circle";
            title = "提示消息";
        }
        if (type == 'error') {
            icon = "fa fa-times-circle";
            title = "错误消息";
        }
        if (type == 'warning') {
            icon = "fa fa-exclamation-circle";
            title = "警告消息";
        }
        top.layer.alert(content, {
            icon: icon,
            title: title,
            btn: ['确认'],
            btnclass: ['btn btn-primary'],
        });
    }
    $.modalMsg = function (content, type) {
        if (type != undefined) {
            var icon = "";
            if (type == 'success') {
                icon = "fa-check-circle";
            }
            if (type == 'error') {
                icon = "fa-times-circle";
            }
            if (type == 'warning') {
                icon = "fa-exclamation-circle";
            }
            top.layer.msg(content, { icon: "fa " + icon, time: 2000, shift: 5 });
            top.$(".layui-layer-msg").find('i.' + icon).parents('.layui-layer-msg').addClass('layui-layer-msg-' + type);
            //top.$(".layui-layer-msg").find('i.' + icon).css("color", "#fff").css("top","10px");
        } else {
            top.layer.msg(content);
        }
    }
    $.modalClose = function () {
        var index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        var $IsdialogClose = top.$("#layui-layer" + index).find('.layui-layer-btn').find("#IsdialogClose");
        var IsClose = $IsdialogClose.is(":checked");
        if ($IsdialogClose.length == 0) {
            IsClose = true;
        }

        if (IsClose) {
            top.layer.close(index);
        } else {
            location.reload();
        }
    }

    $.submitForm = function (options) {
        var defaults = {
            url: "",
            param: [],
            loading: "正在提交数据...",
            success: null,
            close: true
        };
        var options = $.extend(defaults, options);
        $.loading(true, options.loading);
        window.setTimeout(function () {
            if ($('[name=__RequestVerificationToken]').length > 0) {
                options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
            }
            $.ajax({
                url: options.url,
                data: options.param,
                type: "post",
                dataType: "json",
                success: function (data) {
                    if (data.state == "success") {
                        options.success(data);
                        $.modalMsg(data.message, data.state);
                        if (options.close) {
                            setTimeout(function () {
                                $.modalClose();
                            }, 500);
                        }
                    } else {
                        $.modalAlert(data.message, data.state);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $.loading(false);
                    $.modalMsg(errorThrown, "error");
                },
                beforeSend: function () {
                    $.loading(true, options.loading);
                },
                complete: function () {
                    $.loading(false);
                }
            });
        }, 500);
    }
    $.deleteForm = function (options) {
        var defaults = {
            prompt: "您确定要删除该项数据吗？",
            url: "",
            param: [],
            loading: "正在删除数据...",
            success: null,
            close: true
        };
        var options = $.extend(defaults, options);
        if ($('[name=__RequestVerificationToken]').length > 0) {
            options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }
        $.modalConfirm(options.prompt, function (r) {
            if (r) {
                $.loading(true, options.loading);
                window.setTimeout(function () {
                    $.ajax({
                        url: options.url,
                        data: options.param,
                        type: "post",
                        dataType: "json",
                        success: function (data) {
                            options.success(data);
                            if (data.state == "success") {
                                $.modalMsg(data.message, data.state);
                            } else {
                                $.modalAlert(data.message, data.state);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            $.loading(false);
                            $.modalMsg(errorThrown, "error");
                        },
                        beforeSend: function () {
                            $.loading(true, options.loading);
                        },
                        complete: function () {
                            $.loading(false);
                        }
                    });
                }, 500);
            }
        });

    }

    $.fn.formValid = function () {
        return $(this).valid({
            errorPlacement: function (error, element) {
                element.parents('.valid').addClass('has-error');
                element.parents('.has-error').find('i.error').remove();
                element.parents('.has-error').append('<i class="fa fa-exclamation-circle fa-lg form-control-feedback error" data-placement="left" data-toggle="tooltip" title="' + error + '"></i>');
                $("[data-toggle='tooltip']").tooltip();
                if (element.parents('.input-group').hasClass('input-group')) {
                    element.parents('.has-error').find('i.error').css('right', '33px')
                }
            },
            success: function (element) {
                element.parents('.has-error').find('i.error').remove();
                element.parent().removeClass('has-error');
            }
        });
    }
    $.fn.formSerialize = function (formdate) {
        var element = $(this);
        if (!!formdate) {
            for (var key in formdate) {
                var $id = element.find('#' + key);
                var value = $.trim(formdate[key]).replace(/&nbsp;/g, '');
                var type = $id.attr('type');
                if ($id.hasClass("select2-hidden-accessible")) {
                    type = "select";
                }
                switch (type) {
                    case "checkbox":
                        if (value == "1") {
                            $id.attr("checked", 'checked');
                        } else {
                            $id.removeAttr("checked");
                        }
                        break;
                    case "select":
                        $id.val(value).trigger("change");
                        break;
                    default:
                        $id.val(value);
                        break;
                }
            };
            return false;
        }
        var postdata = {};
        element.find('input,select,textarea').each(function (r) {
            var $this = $(this);
            var id = $this.attr('id');
            var type = $this.attr('type');
            switch (type) {
                case "checkbox":
                    postdata[id] = $this.is(":checked") ? "1" : "0";
                    break;
                default:
                    var value = $this.val() == "" ? "&nbsp;" : $this.val();
                    if (!$.request("keyValue")) {
                        value = value.replace(/&nbsp;/g, '');
                    }
                    postdata[id] = value;
                    break;
            }
        });
        if ($('[name=__RequestVerificationToken]').length > 0) {
            postdata["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }
        //console.log(postdata);
        return postdata;
    };

    $.fn.bindSelect = function (options) {
        var defaults = {
            id: "id",
            text: "text",
            search: false,
            url: "",
            param: [],
            change: null,
        };
        var options = $.extend(defaults, options);
        var $element = $(this);
        if (options.url != "") {
            $.ajax({
                url: options.url,
                data: options.param,
                dataType: "json",
                async: false,
                success: function (data) {
                    $.each(data, function (i) {
                        $element.append($("<option></option>").val(data[i][options.id]).html(data[i][options.text]));
                    });
                    $element.select2({
                        minimumResultsForSearch: options.search == true ? 0 : -1
                    });
                    $element.on("change", function (e) {
                        if (options.change != null) {
                            options.change(data[$(this).find("option:selected").index()]);
                        }
                        $("#select2-" + $element.attr('id') + "-container").html($(this).find("option:selected").text().replace(/　　/g, ''));
                    });
                }
            });
        } else {
            $element.select2({
                minimumResultsForSearch: -1
            });
        }
    }

    $.fn.jqGridRowValue = function () {
        var $grid = $(this);
        var selectedRowIds = $grid.jqGrid("getGridParam", "selarrrow");
        if (selectedRowIds != "") {
            var json = [];
            var len = selectedRowIds.length;
            for (var i = 0; i < len ; i++) {
                var rowData = $grid.jqGrid('getRowData', selectedRowIds[i]);
                json.push(rowData);
            }
            return json;
        } else {
            return $grid.jqGrid('getRowData', $grid.jqGrid('getGridParam', 'selrow'));
        }
    }

    $.fn.dataGrid = function (options) {
        var defaults = {
            datatype: "json",
            autowidth: true,
            rownumbers: true,
            shrinkToFit: false,
            gridview: true
        };
        var options = $.extend(defaults, options);
        var $element = $(this);

        if (!options["onSelectRow"]) {

            options["onSelectRow"] = function (rowid) {
                //选择行事件
                var length = $(this).jqGrid("getGridParam", "selrow").length;
                var $initlist = $("#initlist");
                var $btnlist = $("#btnlist");
                if (length > 0) {
                    $initlist.hide(300);
                    $btnlist.show(300);
                } else {
                    $initlist.show(300);
                    $btnlist.hide(300);
                }
                $btnlist.find('.close').click(function () {
                    $initlist.show(300);
                    $btnlist.hide(300);
                    $element.trigger("reloadGrid");
                })
            };
        }
        $element.jqGrid(options);
    };
})(jQuery);